//
//  InteractLabel.swift
//  DYSwiftFramework
//
//  Created by huangdeyu on 2021/11/5.
//  Copyright © 2021 none. All rights reserved.
//

import UIKit


private var tapKey:UInt8  = 0
// 针对UILabel设计的点击事件
extension NSAttributedString:AssociatedObjects {

    // 交互信息
    var interactInfo:(range:NSRange,action:()->Void)? {
        get {
            return associatedObject(for: &tapKey)
        }
        set(value) {
            setAssociatedObject(value, for: &tapKey, policy: .strong)
        }
    }
}

class InteractLabel: UILabel {
    
    init() {
        super.init(frame: CGRect.zero)
        setupLabel()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
    private func setupLabel(){
        isUserInteractionEnabled = true
        let ges = UITapGestureRecognizer.init(target: self, action: #selector(onTap))
        addGestureRecognizer(ges)
    }
    
    @objc func onTap(ges:UITapGestureRecognizer)  {
        let layoutManager = NSLayoutManager()
        let textContainer = NSTextContainer(size: CGSize.zero)
        let textStorage = NSTextStorage(attributedString: self.attributedText!)

        layoutManager.addTextContainer(textContainer)
        textStorage.addLayoutManager(layoutManager)

        textContainer.lineFragmentPadding = 0.0
        textContainer.lineBreakMode = self.lineBreakMode
        textContainer.maximumNumberOfLines = self.numberOfLines
        let labelSize = self.bounds.size
        textContainer.size = labelSize

        let locationOfTouchInLabel = ges.location(in: self)
        let textBoundingBox = layoutManager.usedRect(for: textContainer)
        let textContainerOffset = CGPoint(x: (labelSize.width - textBoundingBox.size.width) * 0.5 - textBoundingBox.origin.x, y: (labelSize.height - textBoundingBox.size.height) * 0.5 - textBoundingBox.origin.y)
        let locationOfTouchInTextContainer = CGPoint(x: locationOfTouchInLabel.x - textContainerOffset.x, y: locationOfTouchInLabel.y - textContainerOffset.y)
        let indexOfCharacter = layoutManager.characterIndex(for: locationOfTouchInTextContainer, in: textContainer, fractionOfDistanceBetweenInsertionPoints: nil)
        print(indexOfCharacter)
    }
}
